package com.abc.recycling.controller;

import com.abc.recycling.model.Order;
import com.abc.recycling.model.User;
import com.abc.recycling.service.OrderService;
import com.abc.recycling.service.CollectorOrderService;
import com.abc.recycling.service.UserService;
import com.abc.recycling.service.RecyclingStationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Controller
@RequestMapping("/orders")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;
    private final UserService userService;
    private final CollectorOrderService collectorOrderService;
    private final RecyclingStationService stationService;

    /**
     * 创建订单页面
     */
    @GetMapping("/create")
    public String showCreateOrderForm(Model model) {
        model.addAttribute("stations", stationService.searchStations(null, PageRequest.of(0, 10)));
        return "order/create";
    }

    /**
     * 订单列表页面
     */
    @GetMapping("/list")
    public String listOrders(
            Authentication authentication,
            Model model,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            log.info("获取订单列表, page={}, size={}", page, size);
            User user = userService.getUserByUsername(authentication.getName());
            String role = user.getRole();
            
            PageRequest pageRequest = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createTime"));
            Page<Order> orders;
            
            if ("ADMIN".equals(role)) {
                // 管理员查看所有订单，并关联用户和回收员信息
                orders = orderService.findAllOrdersWithUserInfo(pageRequest);
            } else if ("COLLECTOR".equals(role)) {
                log.debug("获取回收员订单列表, collectorId={}", user.getId());
                orders = collectorOrderService.getOrdersByCollectorId(user.getId(), pageRequest);
            } else {
                log.debug("获取用户订单列表, userId={}", user.getId());
                orders = orderService.getOrdersByUserIdPaged(user.getId(), pageRequest);
            }
            
            model.addAttribute("orders", orders);
            log.info("订单列表获取成功, 总数: {}", orders.getTotalElements());
            return "order/list";
        } catch (Exception e) {
            log.error("获取订单列表失败: {}", e.getMessage());
            throw e;
        }
    }

    /**
     * 评价订单
     */
    @PostMapping("/rate")
    @ResponseBody
    public String rateOrder(@RequestParam Long orderId, @RequestParam Integer rating, @RequestParam String comment) {
        try {
            orderService.rateOrder(orderId, rating, comment);
            return "success";
        } catch (Exception e) {
            return "error: " + e.getMessage();
        }
    }

    /**
     * 订单详情页面
     */
    @GetMapping("/{id}")
    public String getOrder(@PathVariable Long id, Model model) {
        Order order = orderService.getOrderById(id);
        model.addAttribute("order", order);
        return "orders/detail";
    }

    /**
     * 创建订单
     */
    @PostMapping
    public String createOrder(@ModelAttribute Order order, Authentication authentication) {
        User user = userService.getUserByUsername(authentication.getName());
        order.setUserId(user.getId());
        orderService.createOrder(order);
        return "redirect:/orders";
    }

    @GetMapping("/collector/{collectorId}")
    @ResponseBody
    public Page<Order> getCollectorOrders(
            @PathVariable Long collectorId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            log.info("获取回收员订单, collectorId={}, page={}, size={}", collectorId, page, size);
            PageRequest pageRequest = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createTime"));
            return collectorOrderService.getOrdersByCollectorId(collectorId, pageRequest);
        } catch (Exception e) {
            log.error("获取回收员订单失败: {}", e.getMessage());
            throw e;
        }
    }

    @GetMapping("/collector/{collectorId}/status/{status}")
    @ResponseBody
    public Page<Order> getCollectorOrdersByStatus(
            @PathVariable Long collectorId,
            @PathVariable String status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            log.info("获取回收员状态订单, collectorId={}, status={}, page={}, size={}", 
                    collectorId, status, page, size);
            PageRequest pageRequest = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createTime"));
            return collectorOrderService.getOrdersByCollectorAndStatus(collectorId, status, pageRequest);
        } catch (Exception e) {
            log.error("获取回收员状态订单失败: {}", e.getMessage());
            throw e;
        }
    }

    @GetMapping("/collector/{collectorId}/history")
    @ResponseBody
    public Page<Order> getCollectorOrderHistory(
            @PathVariable Long collectorId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            log.info("获取回收员订单历史, collectorId={}, page={}, size={}", collectorId, page, size);
            PageRequest pageRequest = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createTime"));
            return collectorOrderService.getCollectorOrderHistory(collectorId, pageRequest);
        } catch (Exception e) {
            log.error("获取回收员订单历史失败: {}", e.getMessage());
            throw e;
        }
    }

    @GetMapping("/status/{status}")
    @ResponseBody
    public Page<Order> getOrdersByStatus(
            @PathVariable String status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            log.info("获取状态订单, status={}, page={}, size={}", status, page, size);
            PageRequest pageRequest = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createTime"));
            return collectorOrderService.getOrdersByStatus(status, pageRequest);
        } catch (Exception e) {
            log.error("获取状态订单失败: {}", e.getMessage());
            throw e;
        }
    }
} 